require "ostruct"

module Wondercap
  module UI
    
    module TableMixin
      
      class Table
        def initialize
          @header = []
          @rows = []
        end
        
        def header_col(name, width)
          @header << OpenStruct.new(:name => name, :width => width)
        end
        
        def row
          if !@rows.empty? && @rows.last.length < @header.length
            @rows.last
          else
            new_row = []
            @rows << new_row
            new_row
          end
        end
        
        def to_s
          result = StringIO.new
          
          header_str = @header.map { |he| he.name.ljust(he.width) }.join(" | ")
          result.puts header_str
          result.puts "-" * header_str.length
          
          @rows.each do |row|
            col_index = -1
            result.puts row.map { |re| col_index = col_index + 1; re.to_s.ljust(@header[col_index].width) }.join(" | ")
          end
          
          result.string
        end
      end
      
      def table(&block)
        t = Table.new
        t.instance_eval(&block)
        t.to_s
      end
      
    end
    
  end
end